<?php

namespace App\Common\Libs\Ali;

use App\Common\Libs\Json;
use App\Consts\GlobalSmsConst;
use Illuminate\Support\Facades\Log;
use Mrgoon\AliSms\AliSms;

/**
 * 阿里短息发送
 * Class AliYunSms
 * @package App\Common\Libs\Ali
 */
class AliYunSms
{

    /** @var array $config */
    protected $config;

    /** @var AliSms $client */
    public $client;

    /** @var $instance */
    public static $instance;

    /** @var array $smsTemplateCode */
    protected $smsTemplateCode = [
        GlobalSmsConst::SMS_TEMPLATE_LOGIN => 'SMS_181276318',
        GlobalSmsConst::SMS_TEMPLATE_BIND => 'SMS_181276314',
        GlobalSmsConst::SMS_TEMPLATE_UNBIND => 'SMS_181276314',
        GlobalSmsConst::SMS_TEMPLATE_SIGN => 'SMS_181276316',
        GlobalSmsConst::SMS_TEMPLATE_PASSWORD => 'SMS_181276315',
    ];

    /**
     * AliYunSms constructor.
     * @param array $config
     */
    public function __construct($config = [])
    {
        $config = $config ?: config('aliyunsms');
        $this->config = [
            'access_key' => $config['access_key'] ?? '',
            'access_secret' => $config['access_secret'] ?? '',
            'sign_name' => $config['sign_name'] ?? '',
        ];
        $this->client = new AliSms();
    }

    /**
     * @param array $config
     * @return AliYunSms
     */
    public static function getInstance($config = [])
    {
        if (self::$instance instanceof AliYunSms) {
            return self::$instance;
        }
        return self::$instance = new self($config);
    }

    /**
     * @param $mobile
     * @param $scene
     * @param $code
     * @return mixed|\SimpleXMLElement
     * @preview (object) {
     *               "RequestId": "F1DFD9BE-630F-4C0A-A8DB-33D396E83099",
     *               "Message": "OK",
     *               "BizId": "851611508042505562^0",
     *               "Code": "OK"
     *          }
     */
    public function send($mobile, $scene, $code)
    {
        if (empty($mobile) || empty($scene) || empty($code) || !isset($this->smsTemplateCode[$scene])) {
            Log::channel('sms')->info(Json::encode([
                'mobile' => $mobile,
                'scene' => $scene,
                'code' => $code,
                'result' => false
            ]));
            return false;
        }
        try {
            $params = ['code' => $code];
            $templateCode = $this->smsTemplateCode[$scene];
            $result = $this->client->sendSms($mobile, $templateCode, $params, $this->config);
            $result = (array)$result ?: $result;
        } catch (\Exception $e) {
            $result = ['RequestId' => null, 'Message' => $e->getMessage(), 'Code' => $e->getCode()];
        }
        Log::channel('sms')->info(json_encode([
            'mobile' => $mobile, 'scene' => $scene, 'code' => $code, 'result' => $result
        ]));
        if (isset($result['Code']) && $result['Code'] == 'OK') {
            return true;
        }
        return false;
    }

}
